<template>
    <ul class="alpha">
        <li class="item" 
            v-for="item of letters"  
            :key="item"
            :ref="item"
            @touchstart.prevent='handleTouchstart'
            @touchmove='handleTouchmove'
            @touchend='handleTouchend'
            @click='showWord'
        >{{item}}</li>       
    </ul>
</template>

<script>
export default {
    name :'cityAlpha',
    props:{
        cities:Object
    },
    data() {
        return {
            //触摸事件 标记
            touchStatus:false,

            //侧边栏首字母A距离父元素的 高度
            startY:0,

            //减少handleTouchmove执行频率
            timer:null
        }
    },
    updated() {
        this.startY=this.$refs['A'][0].offsetTop
    },
    methods: {
        //当前点击的字母元素
        showWord(e){
            this.$emit('wordChange', e.target.innerText)
        },
        //侧边栏字母 触摸事件
        handleTouchstart(){
            this.touchStatus=true
        },
        handleTouchmove(e){
            //滑动侧边字母栏 切换当前首字母城市
            if(this.touchStatus){
                if(this.timer){
                    clearTimeout(this.timer)
                }
                setTimeout(() => {
                    //触摸点距离页面的高度 减去 header高度
                    const letterY=e.touches[0].clientY-79
                    //当前触摸字母的序号
                    const index=Math.floor((letterY-this.startY)/20)
                    if(index>=0 && index<this.letters.length){
                        this.$emit('wordChange', this.letters[index])
                    }   
                }, 16);            
            }
        },
        handleTouchend(){
            this.touchStatus=false
        }
    },
    computed: {
        //一个字母表数组
        letters(){
            const letters=[]
            for(let i in this.cities){
                letters.push(i)
            }
            return letters
        }
    },
}
</script>

<style lang="stylus" scoped>
    @import '~styles/varibles.styl';
    .alpha
        display: flex
        flex-direction:column 
        justify-content:center
        position:absolute
        right:0
        top:1.58rem
        bottom:0
        width :.4rem 
        .item
            line-height :.4rem
            text-align :center
            color:$bgColor
</style>